#!/usr/bin/python
# coding=utf-8
# author=He


import MySQLdb
import config


class Connect:

    __connect = ''
    __cursor = ''

    def __init__(self):

        try:
            self.__connect = MySQLdb.connect(host=config.db_host, user=config.db_user, passwd=config.db_password,
                                             port=config.db_port)
            self.__connect.set_character_set(charset=config.db_charset)

            self.__cursor = self.__connect.cursor()

        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def select_db(self, db_name=''):

        if not db_name:
            db_name = config.db_name

        try:
            self.__connect.select_db(db_name)
        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def query(self, sql):
        try:
            result = self.__cursor.execute(sql)
            return result
        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def query_row(self, sql):
        try:
            self.query(sql)
            result = self.__cursor.fetchone()
            return result
        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def query_all(self, sql):
        try:
            self.query(sql=sql)
            result = self.__cursor.fetchall()
            desc = self.__cursor.description
            d = []
            for inv in result:
                _d = {}
                for i in range(0, len(inv)):
                    _d[desc[i][0]] = str(inv[i])
                d.append(_d)
            return d

        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def insert(self, table_name, data):

        try:
            for key in data:
                data[key] = "'" + str(data[key]) + "'"
            key = ','.join(data.keys())
            value = ','.join(data.values())

            real_sql = "INSERT INTO " + table_name + " (" + key + ") VALUES (" + value + ")"
            # self.query("set names 'utf8'")
            self.query(real_sql)
            self.commit()
            return self.get_last_insert_id()

        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def update(self, sql_string):
        try:
            cursor = self.__cursor()
            cursor.execute(sql_string)
            self.commit()
            cursor.close()
            self.close()
        except MySQLdb.Error as e:
            print("MySQLdb Error %d: %s" % (e.args[0], e.args[1]))

    def get_last_insert_id(self):
        return self.__cursor.lastrowid

    def rowcount(self):
        return self.__cursor.rowcount

    def commit(self):
        self.__connect.commit()

    def close(self):
        self.__connect.close()
        self.__cursor.close()
